package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.config.Menu;
import com.ych.modules.base.dbEntity.TSysMenuEntity;
import com.ych.modules.base.mapper.TSysMenuMapper;
import com.ych.modules.base.service.ITSysMenuService;
import com.ych.modules.base.service.ITUserInfoService;
import com.ych.modules.sql.service.ISysSqlService;
import com.ych.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/5
 * Time: 15:48
 * Description:
 */
@Service("ITSysMenuService")
public class TSysMenuServiceImpl extends ServiceImpl<TSysMenuMapper, TSysMenuEntity> implements ITSysMenuService {

    @Autowired
    private ITUserInfoService    itUserInfoService;
    @Autowired
    private RSysRoleMenuServiceImpl rSysRoleMenuService;
    @Autowired
    private ISysSqlService iSysSqlService;

    @Override
    public List<TSysMenuEntity> queryListParentId(String parentId) {
        Wrapper<TSysMenuEntity> wrapper = new EntityWrapper<TSysMenuEntity>()
                .where("1=1")
                .eq("parent_id", parentId)
                .orderBy("`order_num` ASC");
        return this.selectList(wrapper);
    }

    @Override
    public List<TSysMenuEntity> queryNotButtonList() {
        Wrapper<TSysMenuEntity> wrapper = new EntityWrapper<TSysMenuEntity>()
                .where("1=1")
                .ne("type", 2) //不等于
                .orderBy("`order_num` ASC");
        return this.selectList(wrapper);


    }

    @Override
    public List<TSysMenuEntity> getUserMenuList(String userId) {
        //系统管理员，拥有最高权限
        if (("1").equals(userId)) {
            return getAllMenuList(null);
        }

        //用户菜单列表
        List<String> menuIdList = itUserInfoService.queryAllMenuId(userId);
        return getAllMenuList(menuIdList);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delete(String menuId) {
        //删除菜单
        this.deleteById(menuId);
        //删除菜单与角色关联
        rSysRoleMenuService.deleteByMap(new MapUtils().put("menu_id", menuId));
    }

    /**
     * 获取所有菜单列表
     */
    private List<TSysMenuEntity> getAllMenuList(List<String> menuIdList) {
        //查询根菜单列表
        List<TSysMenuEntity> menuList = queryListParentId("0", menuIdList);
        //递归获取子菜单
        getMenuTreeList(menuList, menuIdList);

        return menuList;
    }

    @Override
    public List<TSysMenuEntity> queryListParentId(String parentId, List<String> menuIdList) {
        List<TSysMenuEntity> menuList = queryListParentId(parentId);
        if (menuIdList == null) {
            return menuList;
        }

        List<TSysMenuEntity> userMenuList = new ArrayList<>();
        for (TSysMenuEntity menu : menuList) {
            if (menuIdList.contains(menu.getMenuId())) {
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    /**
     * 递归
     */
    private List<TSysMenuEntity> getMenuTreeList(List<TSysMenuEntity> menuList, List<String> menuIdList) {
        List<TSysMenuEntity> subMenuList = new ArrayList<>();

        for (TSysMenuEntity entity : menuList) {
            //目录
            if (Menu.MenuType.CATALOG.getValue().equals(entity.getMenuType())) {
                entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
            }
            subMenuList.add(entity);
        }

        return subMenuList;
    }
    @Override
    public Set<String> permsByUserId(String userId) {
        Set<String> permsSet = new HashSet<>();
        if ("1".equals(userId)) {
            Wrapper<TSysMenuEntity> wrapper = new EntityWrapper<TSysMenuEntity>()
                    .where("1=1")
                    .isNotNull("perms")
                    .and("perms !=''");
            List<TSysMenuEntity> menuList = this.selectList(wrapper);
            for (TSysMenuEntity menu : menuList) {
                permsSet.addAll(Arrays.asList(menu.getPerms().trim().split(",")));
            }
        } else {
            String sql = "SELECT m.perms AS var1 FROM r_user_info_sys_role ur LEFT JOIN r_sys_role_menu rm ON ur.role_id = rm.role_id LEFT JOIN t_sys_menu m ON rm.menu_id = m.menu_id WHERE m.perms IS NOT NULL and perms !='' AND ur.user_id = '" + userId + "'";
            List<Map<String, Object>> listMap = iSysSqlService.selectSql(sql);
            for (Map<String, Object> map : listMap) {
                String val = (String) map.get("var1");
                permsSet.addAll(Arrays.asList(val.trim().split(",")));
            }
        }
        return permsSet;
    }
}
